import sys
from PySide6.QtWidgets import QApplication, QWidget
from PySide6.QtGui import QPixmap
from qtbuild.ui_home import Ui_Form

from PySide6.QtNetwork import QUdpSocket, QHostAddress


class MainUI(QWidget):
    led_status = 0  # LED灯状态 0未知 1点亮 2熄灭

    def __init__(self) -> None:
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.btnSend.clicked.connect(self.btnLEDHandle)
        self.socket = QUdpSocket(self)
        self.socket.bind(QHostAddress("192.168.99.158"), 9528)
        self.socket.readyRead.connect(self.dataReceive)
        msg = "LED_OFF"
        s_msg = msg.encode()
        self.socket.writeDatagram(
            s_msg, QHostAddress("192.168.88.58"), 9527)

    def dataReceive(self):
        # hasPendingDatagrams()来判断是否还有要读取的数据,
        # 如果有的话就调用readDatagram()来读取数据，传入该方法的参数为要读取的数据大小，我们可以用pendingDatagramSize()方法获取。
        while self.socket.hasPendingDatagrams():
            msglist = self.socket.readDatagram(
                self.socket.pendingDatagramSize())
            msg = msglist[0]
            print(msg)
            if msg == "LED_OFF":
                self.led_status = 2
                self.ui.btnSend.setText("OFF")
                self.ui.LED.setPixmap(QPixmap(':/image/dengpao1hao.png'))
            elif msg == "LED_ON":
                self.led_status = 1
                self.ui.btnSend.setText("ON")
                self.ui.LED.setPixmap(QPixmap(':/image/dengpao5hao.png'))

    def btnLEDHandle(self):
        if self.led_status == 1:
            msg = "LED_OFF"
            s_msg = msg.encode()
            self.socket.writeDatagram(
                s_msg, QHostAddress("192.168.88.58"), 9527)
        else:
            msg = "LED_ON"
            s_msg = msg.encode()
            self.socket.writeDatagram(
                s_msg, QHostAddress("192.168.88.58"), 9527)


app = QApplication(sys.argv)
home = MainUI()
home.show()
app.exit(app.exec())
